package cn.broadin.app.hotel.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import cn.broadin.app.hotel.MainActivity;
import cn.broadin.app.hotel.app.AppConfig;
import cn.broadin.app.hotel.app.AppContext;
import cn.broadin.app.hotel.task.BootVideoTask;
import cn.broadin.app.hotel.task.FireCheckTask;
import cn.broadin.app.hotel.task.IndexADTask;
import cn.broadin.app.hotel.util.XHttpProxy;
import cn.broadin.app.hotel.util.XLog;
import cn.broadin.app.hotel.util.XToast;
import cn.broadin.app.hotel.util.XUtils;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

/**
 * 
 * 在线升级Service
 * 
 * @author   long
 * @version  1.0.0
 * @date 2016年1月5日上午11:34:00
 */
public class ListenNewVersionService extends Service {
	int curVerCode;
	int serverVerCode;
	String stbStateUrl;
	String fireStateUrl;
	String updateIP;
	private static final int MSG_GET_VERCODE = 1;
	private static final int MSG_AJAX_SUCCESS = 0;
    private static final int MSG_AJAX_ERROR = -1;
    private static final int NOTIFICATION_ID = 1314;
    
    public static boolean isRunning = false;
    public static Service mService;
    public String productInfo = "";
    public String macNum = "";
    public String startVideoUrl = "";
    public String indexVideoUrl = "";
    
	@Override
	public void onCreate() {
		super.onCreate();
		
		AppContext appContext = (AppContext)getApplicationContext();  //获取全局变量app
		productInfo = appContext.getProductInfo();
		startVideoUrl = appContext.getStartVideoUrl();
		indexVideoUrl = appContext.getIndexVideoUrl();

		mService = this;
		isRunning = true;
		
		XLog.d("service onCreate");
	}

	@Override
	public void onDestroy() {
		XLog.d("service onDestroy");
		
		mService = null;
		isRunning = false;
		
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		XLog.i("BootVideoTask1111-----productInfo = " + productInfo);
		Bundle bundle = (Bundle)intent.getExtras();
		stbStateUrl = bundle.getString("stbStateUrl");
		fireStateUrl = bundle.getString("fireStateUrl");
		macNum = bundle.getString("macNum");
		XLog.i("stbStateUrl=" + stbStateUrl);
		XLog.i("fireStateUrl=" + fireStateUrl);
		
		// 启动线程 检测开机视频是否有更新
		String saveDirPath = "";
		String IndexVideosavePath = "";

		if(productInfo == null || productInfo.equals("")) {  //再获取一次厂家信息
			productInfo = XUtils.getSystemInfo();
		}
		
		XLog.i("productInfo=" + productInfo);
		
		if(productInfo.equals("MBX")) {  //智诺达S805方案
			saveDirPath = "/mnt/sdcard";
		} else if(productInfo.equals("CNCR") || productInfo.equals("JIUZHOU")) { //九州和初灵方案
			saveDirPath = "/data/local";
		} else if(productInfo.equals("Skyworth")) {
			saveDirPath = "/system/media";
		}
		else {  //默认方案
			saveDirPath = "/data/local";
		}
		
		IndexVideosavePath = saveDirPath + "/indexVideo";
		
		
		//下载开机视频广告
		Thread advThread = new Thread(new BootVideoTask(saveDirPath,productInfo,startVideoUrl));
		advThread.setPriority(Thread.MIN_PRIORITY);
		advThread.start();
		
//		//下载首页小视频广告
		Thread IndexADThread = new Thread(new IndexADTask(IndexVideosavePath,indexVideoUrl));
		IndexADThread.setPriority(Thread.MIN_PRIORITY);
		IndexADThread.start();
		
		
		// 启动线程 检测火灾险情
		//Thread fireThread = new Thread(new FireCheckTask(fireStateUrl));
		//fireThread.setPriority(Thread.NORM_PRIORITY);
		//fireThread.start();
		
		
		
		//执行监测机顶盒状态任务
		handler.post(task);
	    
        PendingIntent mPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
		Notification notification = new Notification.Builder(getApplicationContext())
			.setAutoCancel(true)  
			.setContentTitle("开机广告更新").setContentText("开机广告正在更新，请勿关闭！")  
			.setContentIntent(mPendingIntent)  
			.setWhen(System.currentTimeMillis()).build();
		
		startForeground(NOTIFICATION_ID, notification);		//启动前台服务
		
		return START_STICKY;
        //return super.onStartCommand(intent, flags, startId);
	}
	
	private void stbstateCheck() {
		String url = stbStateUrl;
		new requestAjaxData(url, MSG_GET_VERCODE).start();
	}
	
	private void checkVerCode() {
		String url = "http://" + updateIP + "/update/version.json";
		new requestAjaxData(url, MSG_GET_VERCODE).start();
	}
	
	
	private Handler handler = new Handler();    
	
	private Runnable task = new Runnable() {    
	       public void run() {    
	           // TODOAuto-generated method stub  
	             handler.postDelayed(this, 5*1000);//设置延迟时间，此处是5秒  
	             
	              //需要执行的代码  
	             stbstateCheck();
	       }     
	};  
	
	
	
	
	
	
	private class requestAjaxData extends Thread{
		private String Url;
		private int serviceType;
		public requestAjaxData(String Url, int serviceType){
			this.Url = Url;
			this.serviceType = serviceType;
			Log.d("dyh:","requestAjaxData url=" + Url);
		}
		public void run(){
			try {
				String jsonStr = null;  
		        URL url = new URL(Url);  
		        HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 利用HttpURLConnection对象,我们可以从网络中获取网页数据.  
		        conn.setConnectTimeout(5 * 1000);   // 单位是毫秒，设置超时时间为5秒  
		        conn.setRequestMethod("GET");       // HttpURLConnection是通过HTTP协议请求path路径的，所以需要设置请求方式,可以不设置，因为默认为GET
		        if (conn.getResponseCode() == 200) {// 判断请求码是否是200码，否则失败  
		            InputStream is = conn.getInputStream(); // 获取输入流  
		            byte[] data = readStream(is);   // 把输入流转换成字符数组  
		            jsonStr = new String(data);        // 把字符数组转换成字符串  		            
		            Message msg = myHander.obtainMessage();
		            msg.what = serviceType;
		            msg.obj = jsonStr;
		            msg.arg1 = MSG_AJAX_SUCCESS;
		            myHander.sendMessage(msg);//发送message信息        
		        }
			} catch (Exception e) {
				// TODO: handle exception
				Log.d("caolm:","requestAjaxData error");
				Message msg = myHander.obtainMessage();
	            msg.what = serviceType;
	            msg.obj = " ";
	            msg.arg1 = MSG_AJAX_ERROR;
	            myHander.sendMessage(msg);//发送message信息     
				e.printStackTrace();
			}			   
		}
	};
	
	/** 
     * 把输入流转换成字符数组 
     * @param inputStream   输入流 
     * @return  字符数组 
     * @throws Exception 
     */  
    public static byte[] readStream(InputStream inputStream) throws Exception {  
        ByteArrayOutputStream bout = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while ((len = inputStream.read(buffer)) != -1) {  
            bout.write(buffer, 0, len);  
        }  
        bout.close();  
        inputStream.close();  
  
        return bout.toByteArray();  
    } 
    
    private Handler myHander = new Handler() {
    	
    	@SuppressLint("HandlerLeak")
		public void handleMessage(Message msg){
			switch (msg.what){
				case MSG_GET_VERCODE:
					if (msg.arg1 == MSG_AJAX_SUCCESS) {
						//parseVerCode((String)msg.obj);
						
					} else if (msg.arg1 == MSG_AJAX_ERROR) {
						
						Log.d("dyh:","requestVerCode error");
					}
					break;
				default:
					break;
			}
		};
	};
	
}
